<?php

namespace apiend\modules\passport\models;

use Yii;
use common\base\Model;
use apiend\models\User;

/**
 * 密码重置
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class PasswordResetForm extends Model {

    const PASSWORD_PATTERN = '/((?=.*[a-z])(?=.*\d)|(?=[a-z])(?=.*[#@!~%^&*])|(?=.*\d)(?=.*[#@!~%^&*]))[a-z\d#@!~%^&*]{8,16}/i';

    /**
     * @var integer 登录用户ID
     */
    public $user_id;

    /**
     * @var string 密码
     */
    public $password;

    /**
     * @var integer 登录用户ID
     */
    private $_user = null;

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['password'], 'required'],
            ['password', 'string', 'min' => 8, 'max' => 30],
            ['user_id', 'validateUser'],
            [['password'], 'match', 'pattern' => self::PASSWORD_PATTERN, 'message' => '密码过于简单'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'password' => '密码',
            'user_id' => '用户',
        ];
    }

    /**
     * 校验用户是否登录
     * @param string $attribute the attribute currently being validated
     */
    public function validateUser($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        if (!$this->getUser()) {
            $this->addError($attribute, '请登录后再进行密码修改');
        }
    }

    /**
     * 校验用户是否登录
     * @param string $attribute the attribute currently being validated
     */
    public function validateResetToken($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        if (!User::isPasswordResetTokenValid($this->$attribute)) {
            $this->addError($attribute, '校验信息已过期');
        } else {
            $user = $this->getUser();
            if ($user->password_reset_token !== $this->$attribute) {
                $this->addError($attribute, '校验信息不正确');
            }
        }
    }

    /**
     * 获取用户信息
     * @return UserMeta|null
     */
    protected function getUser() {
        if ($this->_user === null) {
            $this->_user = User::findOne($this->user_id);
        }
        return $this->_user;
    }

    /**
     * 重置密码
     * @return boolean whether the password was reset
     */
    public function reset() {
        if (!$this->validate()) {
            $this->dumpError('密码重置失败');
        }
        $user = $this->getUser();
        if (!$user) {
            return $this->dumpError('用户不存在');
        }
        $user->setPassword($this->password);
        $user->removePasswordResetToken();
        if (!$user->save()) {
            $user->dumpError('密码重置失败');
        }
        return true;
    }

}
